<?php
/*
 * @Author: 李志刚
 * @CopyRight: 2020-2030 衡水山木枝技术服务有限公司
 * @Date: 2021-09-11 15:24:28
 * @Description: 租户商品管理
 * @LastEditors: 李志刚
 * @LastEditTime: 2021-09-16 09:59:21
 * @FilePath: /qingshanERP/app/Http/Controllers/Tenant/GoodController.php
 */

namespace App\Http\Controllers\Tenant;

use Validator;
use Illuminate\Http\Request;
use App\Customize\PddRequest;
use App\Models\QingShanERP\Good;
use App\Models\QingShanERP\Shop;
use App\Http\Controllers\Controller;
use App\Models\QingShanERP\GoodSpec;
use App\Models\QingShanERP\GoodSupplier;
use App\Models\QingShanERP\GoodSpecSupplier;
use DB;

class GoodController extends Controller
{
    public function getList(Request $request)
    {
        try {
            $page = $request->input('page', 0);
            $size = $request->input('size', 10);
            $shopid = $request->input('shopid', 0);
            $is_onsale = $request->input('is_onsale', 1);
            $key = $request->input('key', '');
            $tenant_id = $request->tenant->tid;
            $list = Good::with(['shop' => function ($q) {
                $q->select('id', 'shopname');
            }, 'supplier' => function ($q) {
                $q->where('del_flag', 0)->with('supplier');
            }, 'spec'])->where('tenant_id',$tenant_id)->where(function ($q) use ($shopid) {
                if ($shopid != 0) {
                    $q->where('shop_id', $shopid);
                }
            })->where(function ($q) use ($is_onsale) {
                if ($is_onsale != '') {
                    $q->where('is_onsale', $is_onsale);
                }
            })->where(function ($q) use ($key) {
                if ($key != '') {
                    $q->where('shopname', 'like', '%' . $key . '%');
                }
            })->where('del_flag', 0)->offset(($page - 1) * $size)->limit($size)->orderBy('id', 'desc')->get();
            $count = Good::where('tenant_id',$tenant_id)->where(function ($q) use ($shopid) {
                if ($shopid != 0) {
                    $q->where('shop_id', $shopid);
                }
            })->where(function ($q) use ($is_onsale) {
                if ($is_onsale != '') {
                    $q->where('is_onsale', $is_onsale);
                }
            })->where(function ($q) use ($key) {
                if ($key != '') {
                    $q->where('shopname', 'like', '%' . $key . '%');
                }
            })->where('del_flag', 0)->count();
            $res = ['list' => $list, 'total' => $count];
            return $this->resData(200, '获取数据成功...', $res);
        } catch (\Throwable $e) {
            return $this->resData(500, '获取数据失败，请稍后再试...');
        }
    }
    public function postSpecList(Request $request)
    {
        try {
            $validator = Validator::make($request->input(), [
                'good_id' => 'required|integer',
            ]);
            $attrs = array(
                'good_id' => '商品ID'
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                // 如果有错误，提示第一条
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $good_id = $request->input('good_id');
            $good_spec = GoodSpec::where('good_id', $good_id)->where('del_flag', 0)->get();
            return $this->resData(200, '查询成功...', $good_spec);
        } catch (\Throwable $e) {
            return $this->resData(500, '查询失败，请重新操作...');
        }
    }
    // 按门店同步商品
    public function postSync(Request $request)
    {
        if (!$request->tenant->super) {
            return $this->resData(400, '此账户无管理权限...');
        }
        DB::beginTransaction();
        try {
            $shopid = $request->input('shopid', 0);
            $shop = Shop::where('del_flag', 0)->where('status', 1)->where('id', $shopid)->first();
            if (is_null($shop)) {
                DB::rollback();
                return $this->resData(400, '没有这个门店，请先在后台添加！');
            }
            switch ($shop->type) {
                case 4:
                    // 拼多多商品同步
                    $params['access_token'] = PddRequest::getToken($shopid);
                    if (is_null($params['access_token'])) {
                        DB::rollback();
                        return $this->resData(400, '此门店授权已过期，请先重新授权...');
                    }
                    $params['page_size'] = 100;
                    $params['page'] = 1;
                    $has_next = true;
                    $goods_list = [];
                    while ($has_next) {
                        $result = PddRequest::request('pdd.goods.list.get', $params);
                        if (isset($result['goods_list_get_response'])) {
                            $has_next = $result['goods_list_get_response']['total_count'] >= 100 ? true : false;
                            if ($has_next) {
                                $params['page'] = $params['page'] + 1;
                            }
                            if (is_array($result['goods_list_get_response']['goods_list'])) {
                                $goods_list = array_merge($goods_list, $result['goods_list_get_response']['goods_list']);
                            }
                        } else {
                            break;
                            DB::rollback();
                            return $this->resData(500, '获取数据失败，请稍后再试...' . $result['error_response']['error_msg']);
                        }
                    }
                    $date = date('Y-m-d H:i:s');
                    $all_good = Good::where('shop_id', $shop->id)->where('del_flag', 0)->get();
                    foreach ($goods_list as $g) {
                        // 判断是否存在
                        $cg = ['tenant_id' => $request->tenant->tid,'type' => $shop->type, 'shop_id' => $shop->id, 'goods_id' => $g['goods_id'], 'goods_name' => $g['goods_name'], 'thumb_url' => $g['thumb_url'], 'image_url' => $g['image_url'], 'is_more_sku' => $g['is_more_sku'], 'is_onsale' => $g['is_onsale']];
                        $c = $all_good->where('goods_id', $g['goods_id'])->first();
                        if (is_null($c)) {
                            $c = Good::create($cg);
                        } else {
                            Good::where('id', $c->id)->update($cg);
                        }
                        $all_good_spec = GoodSpec::where('good_id', $c->id)->where('del_flag', 0)->get();
                        $cgs = [];
                        foreach ($g['sku_list'] as $s) {
                            $cs = $all_good_spec->where('sku_id', $s['sku_id'])->first();
                            if (!is_null($cs)) {
                                GoodSpec::where('id', $cs->id)->update(['spec' => $s['spec'], 'sku_id' => $s['sku_id'], 'is_sku_onsale' => $s['is_sku_onsale']]);
                            } else {
                                $cgs[] = ['good_id' => $c->id, 'spec' => $s['spec'], 'sku_id' => $s['sku_id'], 'is_sku_onsale' => $s['is_sku_onsale'], 'created_at' => $date, 'updated_at' => $date];
                            }
                        }
                        if (count($cgs) > 0) {
                            GoodSpec::insert($cgs);
                        }
                    }
                    break;

                default:
                    break;
            }
            DB::commit();
            return $this->resData(200, '同步数据成功...');
        } catch (\Throwable $e) {
            DB::rollback();
            // dd($e->getMessage());
            return $this->resData(500, '获取数据失败，请稍后再试...');
        }
    }
    // 供应商商品名称
    public function postGNList(Request $request)
    {
        try {
            $good_id = $request->input('good_id', 0);
            $list = GoodSupplier::with(['supplier'])->where('good_id', $good_id)->where('del_flag', 0)->orderBy('id', 'desc')->get();
            return $this->resData(200, '获取数据成功...', $list);
        } catch (\Throwable $e) {
            return $this->resData(500, '获取数据失败，请稍后再试...');
        }
    }
    public function postGNCreate(Request $request)
    {
        try {
            $validator = Validator::make($request->input(), [
                'good_id' => 'required|integer',
                'supplier_id' => 'required|integer',
                'good_name' => 'required|max:200',
            ]);
            $attrs = array(
                'good_id' => '商品',
                'supplier_id' => '供应商',
                'good_name' => '对应名称'
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                // 如果有错误，提示第一条
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $all = $request->all();
            // 有过的话不让添加
            if (!is_null(GoodSupplier::where('good_id', $all['good_id'])->where('supplier_id', $all['supplier_id'])->where('del_flag', 0)->first())) {
                return $this->resData(400, '已经存在过了，请直接修改');
            }
            $create = ['good_id' => $all['good_id'], 'supplier_id' => $all['supplier_id'], 'good_name' => $all['good_name']];
            GoodSupplier::create($create);
            return $this->resData(200, '添加成功...');
        } catch (\Throwable $e) {
            return $this->resData(500, '添加失败，请重新操作...');
        }
    }
    public function postGNEdit(Request $request)
    {
        try {
            $validator = Validator::make($request->input(), [
                'good_supplier_id' => 'required|integer',
                'good_name' => 'required|max:200',
            ]);
            $attrs = array(
                'good_supplier_id' => '商品ID',
                'good_name' => '对应名称'
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                // 如果有错误，提示第一条
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $all = $request->all();
            $update = ['good_name' => $all['good_name']];
            GoodSupplier::where('id', $all['good_supplier_id'])->update($update);
            return $this->resData(200, '添加成功...');
        } catch (\Throwable $e) {
            return $this->resData(500, '添加失败，请重新操作...');
        }
    }
    public function postGNDetail(Request $request)
    {
        try {
            $validator = Validator::make($request->input(), [
                'good_supplier_id' => 'required|integer',
            ]);
            $attrs = array(
                'good_supplier_id' => '商品ID'
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                // 如果有错误，提示第一条
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $good_supplier_id = $request->input('good_supplier_id');
            $goodsupplier = GoodSupplier::where('id', $good_supplier_id)->first();
            return $this->resData(200, '添加成功...', $goodsupplier);
        } catch (\Throwable $e) {
            return $this->resData(500, '添加失败，请重新操作...');
        }
    }
    public function postGNRemove(Request $request)
    {
        try {
            $validator = Validator::make($request->input(), [
                'good_supplier_id' => 'required|integer',
            ]);
            $attrs = array(
                'good_supplier_id' => '商品ID'
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                // 如果有错误，提示第一条
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $good_supplier_id = $request->input('good_supplier_id');
            GoodSupplier::where('id', $good_supplier_id)->update(['del_flag' => 1]);
            return $this->resData(200, '添加成功...');
        } catch (\Throwable $e) {
            return $this->resData(500, '添加失败，请重新操作...');
        }
    }
    // 供应商规格名称
    public function postSNList(Request $req)
    {
        try {
            $good_id = $req->input('good_id', 0);
            $list = GoodSpecSupplier::with(['supplier', 'goodspec'])->where('good_id', $good_id)->where('del_flag', 0)->orderBy('id', 'desc')->get();
            return $this->resData(200, '获取数据成功...', $list);
        } catch (\Throwable $e) {
            return $this->resData(500, '获取数据失败，请稍后再试...');
        }
    }
    public function postSNCreate(Request $request)
    {
        try {
            $validator = Validator::make($request->input(), [
                'good_id' => 'required|integer',
                'good_spec_id' => 'required|integer',
                'supplier_id' => 'required|integer',
                'spec' => 'required|max:200',
                'price' => 'required|numeric|min:0',
                'shipping' => 'required|numeric|min:0',
            ]);
            $attrs = array(
                'good_id' => '商品',
                'good_spec_id' => '商品规格',
                'supplier_id' => '供应商',
                'spec' => '对应名称',
                'price' => '进货价',
                'shipping' => '运费',
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                // 如果有错误，提示第一条
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $all = $request->all();
            // 有过的话不让添加
            if (!is_null(GoodSpecSupplier::where('good_spec_id', $all['good_spec_id'])->where('supplier_id', $all['supplier_id'])->where('del_flag', 0)->first())) {
                return $this->resData(400, '已经存在过了，请直接修改');
            }
            $create = ['good_id' => $all['good_id'], 'good_spec_id' => $all['good_spec_id'], 'supplier_id' => $all['supplier_id'], 'spec' => $all['spec'], 'price' => $all['price'], 'shipping' => $all['shipping']];
            GoodSpecSupplier::create($create);
            return $this->resData(200, '添加成功...');
        } catch (\Throwable $e) {
            return $this->resData(500, '添加失败，请重新操作...', $e->getMessage());
        }
    }
    public function postSNEdit(Request $request)
    {
        try {
            $validator = Validator::make($request->input(), [
                'good_spec_supplier_id' => 'required|integer',
                'spec' => 'required|max:200',
                'price' => 'required|numeric|min:0',
                'shipping' => 'required|numeric|min:0',
            ]);
            $attrs = array(
                'good_spec_supplier_id' => '商品ID',
                'spec' => '对应名称',
                'price' => '进货价',
                'shipping' => '运费',
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                // 如果有错误，提示第一条
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $all = $request->all();
            $update = ['spec' => $all['spec'], 'price' => $all['price'], 'shipping' => $all['shipping']];
            GoodSpecSupplier::where('id', $all['good_spec_supplier_id'])->update($update);
            return $this->resData(200, '添加成功...');
        } catch (\Throwable $e) {
            return $this->resData(500, '添加失败，请重新操作...');
        }
    }
    public function postSNDetail(Request $request)
    {
        try {
            $validator = Validator::make($request->input(), [
                'good_spec_supplier_id' => 'required|integer',
            ]);
            $attrs = array(
                'good_spec_supplier_id' => '商品ID'
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                // 如果有错误，提示第一条
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $good_spec_supplier_id = $request->input('good_spec_supplier_id');
            $goodsupplier = GoodSpecSupplier::where('id', $good_spec_supplier_id)->first();
            return $this->resData(200, '查询成功...', $goodsupplier);
        } catch (\Throwable $e) {
            return $this->resData(500, '查询失败，请重新操作...');
        }
    }
    public function postSNRemove(Request $request)
    {
        try {
            $validator = Validator::make($request->input(), [
                'good_spec_supplier_id' => 'required|integer',
            ]);
            $attrs = array(
                'good_spec_supplier_id' => '商品ID'
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                // 如果有错误，提示第一条
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $good_spec_supplier_id = $request->input('good_spec_supplier_id');
            GoodSpecSupplier::where('id', $good_spec_supplier_id)->update(['del_flag' => 1]);
            return $this->resData(200, '添加成功...');
        } catch (\Throwable $e) {
            return $this->resData(500, '添加失败，请重新操作...');
        }
    }
}
